<template>
  <div>
    <el-dialog
      :title="title"
      v-model="visable"
      width="35%"
      :close-on-click-modal="false"
      :draggable="true"
      style="max-width: 650px;"
    >
      <div class="bs-dialog">
        <el-form
          ref="addRef"
          :model="dialogFormData"
          :rules="dialogFormRules"
          label-width="auto"
          style="width: 95%;padding-left: 5%;text-align: left;"
        >
        <el-form-item label="选择模式: " prop="mode" id="mode">
          <el-radio-group v-model="dialogFormData.mode" fill="#6cf" @change="modeChange">
              <el-radio-button label="合约模式" :value="0" />
              <el-radio-button label="仅学员模式" :value="1" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="合约代码:" prop="instrumentCode" v-if="dialogFormData.mode == 0">
          <el-select
            filterable
            allow-create
            default-first-option
            v-model="dialogFormData.instrumentCode"
            placeholder="请选择练合约代码" 
            @change="searchStudent"
            clearable
          >
            <el-option
              v-for="item in unExpirationDataList"
              :key="item.instrumentCode"
              :label="item.instrumentCode"
              :value="item.instrumentCode"
            >
                <span>{{ item.instrumentCode }}</span>
                <span style="float: right;color: #c7c7c7;">{{ item.instrumentName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="持仓类别:" prop="content">
          <el-checkbox-group v-model="dialogFormData.vipServer" @change="vipServerChange">
            <el-checkbox label="全选" value="全选" />
            <el-checkbox label="已持仓" value="已持仓" />
            <el-checkbox label="未持仓" value="未持仓" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="一对一类别:" prop="content">
          <el-checkbox-group v-model="dialogFormData.vipServer" @change="vipServerChange">
            <el-checkbox label="商品" value="商品" />
            <el-checkbox label="股指" value="股指" />
            <el-checkbox label="ETF" value="ETF" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="账号等级:" prop="studentIDSet" >
          <el-select
            v-model="dialogFormData.studentIDSet"
            multiple
            placeholder="请选择学员"
            @change="studentChange"
          >
          <template #header>
            <el-checkbox
              v-model="checkAll"
              :indeterminate="indeterminate"
              @change="handleCheckAll"
            >
              全选 / 取消全选
            </el-checkbox>
            <el-checkbox
              :disabled="checkAll"
              :model-value="hasHoldCurrentInstrumentCodeCheck==true"
              @change="(checked)=>selectHasHoldCurrentInstrumentCode(checked,true)"
              style="color:#3697fb;"
            >
              已持
            </el-checkbox>
            <el-checkbox
              :model-value="hasHoldCurrentInstrumentCodeCheck==false"
              :disabled="checkAll"
              @change="(checked)=>selectHasHoldCurrentInstrumentCode(checked,false)"
              style="color:red;"
            >
              未持
            </el-checkbox>
          </template>
            <el-option
              v-for="item in studentShowList"
              :key="item.id"
              :label="item.code+'-'+item.wechatNickname+'-'+item.phone"
              :value="item.id"
            >
                <span>{{ item.name }}-{{ item.phone }}</span>
                <span style="float: right;color: #c7c7c7;">
                  {{ item.account }}
                  <span v-if="item.holdCurrentInstrumentCode==true" style="color:#3697fb;">已持</span>
                  <span v-else style="color:red;">未持</span>
                </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学员选择:" prop="studentIDSet" >
          <el-select
            v-model="dialogFormData.studentIDSet"
            multiple
            placeholder="请选择学员"
            @change="studentChange"
          >
          <template #header>
            <el-checkbox
              v-model="checkAll"
              :indeterminate="indeterminate"
              @change="handleCheckAll"
            >
              全选 / 取消全选
            </el-checkbox>
            <el-checkbox
              :disabled="checkAll"
              :model-value="hasHoldCurrentInstrumentCodeCheck==true"
              @change="(checked)=>selectHasHoldCurrentInstrumentCode(checked,true)"
              style="color:#3697fb;"
            >
              已持
            </el-checkbox>
            <el-checkbox
              :model-value="hasHoldCurrentInstrumentCodeCheck==false"
              :disabled="checkAll"
              @change="(checked)=>selectHasHoldCurrentInstrumentCode(checked,false)"
              style="color:red;"
            >
              未持
            </el-checkbox>
          </template>
            <el-option
              v-for="item in studentShowList"
              :key="item.id"
              :label="item.code+'-'+item.wechatNickname+'-'+item.phone"
              :value="item.id"
            >
                <span>{{ item.name }}-{{ item.phone }}</span>
                <span style="float: right;color: #c7c7c7;">
                  {{ item.account }}
                  <span v-if="item.holdCurrentInstrumentCode==true" style="color:#3697fb;">已持</span>
                  <span v-else style="color:red;">未持</span>
                </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="投资建议:" prop="content">
          <el-input type="textarea" :rows="6" v-model="dialogFormData.content" placeholder="请输入投资建议"  clearable/>
        </el-form-item>
        <el-form-item label="发送方式: " prop="sendType">
            <el-select v-model="dialogFormData.sendType" placeholder="请选择发送方式" collapse-tags clearable>
                <el-option label="立即 (审批通过后)" :value="0" />
                <el-option label="定时" :value="1" />
            </el-select>
        </el-form-item>
        <el-form-item label="发送时间:" prop="sendTime" v-if="dialogFormData.sendType==1">
          <el-date-picker
            v-model="dialogFormData.sendTime"
            type="datetime"
            placeholder="请选择发送时间"
            size="small"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

      </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" style="text-align: right;margin-right: 7.5%;">
          <el-button  size="small" @click="visable = false"> 取消 </el-button>
          <el-button  size="small" type="primary" @click="save"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { addItem, getItemByID } from '@/api/oss/advice.js'
import { getAll, getByInstrumentCode } from '@/api/oss/student.js'
import { getUnExpirationData } from '@/api/oss/instrument.js'
// (修改和新增共用一个弹窗时,this.$refs['xxx'].resetFields()函数失效, 因此使用这种方式重置表单数据)
let orgDialogFormData = {
        id: undefined,
        mode:0,
        instrumentCode:"",
        content:"",
        studentIDSet:[],
        status:"",
        // 如果是立即发送 , 发送时间为空且在审批后立即调用发送接口
        sendTime:"",
        sendType:"",
        remark:"",
      }
export default {
  data() {
    return {
      // 是全选
      checkAll:false,
      indeterminate:false,
      title:"",
      visable: false,
      dialogFormData: { ...orgDialogFormData},
      dialogFormRules: {
        instrumentCode: [
          { required: true, message: '请输入合约品种', trigger: ['blur', 'change'] },
        ],
        studentIDSet: [
          { required: true, message: '请选择学员信息', trigger: ['blur', 'change'] },
        ],
        content: [
          { required: true, message: '请输入投资建议', trigger: ['blur', 'change'] },
        ],
        sendType: [
          { required: true, message: '请选择发送方式', trigger: ['blur', 'change'] },
        ],
        sendTime: [
          { required: true, validator:this.validateSendTime, trigger: ['blur', 'change'] },
        ],
      },
      // 页面展示的学员列表
      studentShowList:[],
      // 学员列表
      studentList:[],
      // 合约品种对应的学员列表(仅合约模式)
      instrumentCodeStudentList:[],
      // 期权类型列表
      optionTypeList:[],
      // 未过期的合约代码
      unExpirationDataList:[],
      // 持有 和 未持有勾选 false=选中未持有 true=选中持有 undefined 都不勾选
      hasHoldCurrentInstrumentCodeCheck:undefined,
    }
  },
  methods: {
    studentChange(){
      console.log("总长度=",this.studentList.length,"; 已选中的长度=",this.dialogFormData.studentIDSet.length);
      if (this.studentShowList.length == this.dialogFormData.studentIDSet.length) {
        this.indeterminate = false
        this.checkAll = true
      } else {
        this.indeterminate = true
        this.checkAll = false
      }
    },
    // 切换模式
    modeChange(mode){
      // 切换模式 , 清空之前的全选
      this.checkAll = false
      this.indeterminate = true
      this.dialogFormData.studentIDSet = []
      if (mode == 1) {
        // 获取所有学员信息
        getAll({}).then(res=>{
          if (res.code == 1) {
            this.studentList = res.data
            this.studentShowList = [...res.data]
          }
        })
      } else {
        this.studentShowList = [...this.instrumentCodeStudentList]
      }
    },
    // 搜索学员信息
    searchStudent(){
      if (this.isNotBlank(this.dialogFormData.instrumentCode)) {
        getByInstrumentCode({instrumentCode:this.dialogFormData.instrumentCode}).then(res=>{
          if (res.code == 1) {
            this.instrumentCodeStudentList = res.data
            this.studentShowList = [...res.data]
          }
        })
      }
    },
    // 全选/取消全选
    handleCheckAll(){
      this.hasHoldCurrentInstrumentCodeCheck = undefined
      if (this.checkAll == true) {
        this.indeterminate = false
        this.dialogFormData.studentIDSet = this.studentShowList.map(item=>item.id)
      } else {
        this.indeterminate = true
        this.dialogFormData.studentIDSet = []
      }
    },
    // 选择持有/未持有的合约信息
    selectHasHoldCurrentInstrumentCode(checked,flag){
      this.hasHoldCurrentInstrumentCodeCheck = flag

      console.log('选择持有/未持有的合约信息',checked,flag);
      if (checked == true) {
        this.dialogFormData.studentIDSet = this.studentShowList.filter(item=>item.holdCurrentInstrumentCode == flag).map(item=>item.id)
      } else {
        this.dialogFormData.studentIDSet = []
        this.hasHoldCurrentInstrumentCodeCheck = undefined
      }
    },
    validateSendTime(rule, value, callback){
      if (this.dialogFormData.sendType == 1) {
        if(value) {
          let flag = this.disabledDate(value)
          if (flag == true) {
            callback(new Error('发送时间不能小于当前时间的后30分钟的时间'))
          } else {
            callback()
          }
        } else {
           callback(new Error('发送时间不能为空'))
        }
      }
    },
    // 日期不可选部分(小于当前天数不可选)
    disabledDate(dateString){
      let date =  new Date(Date.parse(dateString))
      let destDate =  new Date()
      let differenceSeconds = (date.getTime() - destDate.getTime()) / 1000
      return differenceSeconds < 30*60
    },
    openModal(id) {
      this.visable = true
      this.$nextTick(() => {
        this.dialogFormData = {...orgDialogFormData}
        if (this.isNotBlank(id)) {
          this.title = '修改投资建议信息'
          // 获取修改的信息
          getItemByID({ 'id': id }).then(res => {
            console.log("修改返回值=",res);
            if (res.code === 1) {
              this.dialogFormData = {...res.data}
            }
          })
        } else {
          this.title = '新增投资建议信息'
        }
        getUnExpirationData({}).then(res => {
          if (res.code == 1) {
            this.unExpirationDataList = [...res.data]
          }
        })
      })
    },
    
    // 保存
    save() {
      this.$refs['addRef'].validate((valid) => {
        if (valid) {
          if (this.isBlank(this.dialogFormData.id)) {
            addItem(this.dialogFormData).then(res => {
              if (res.code == 1) {
                this.$message.success('操作成功')
                this.visable = false
                // 刷新父组件中的表格数据
                this.$emit('flushTable', {})
              } else {
                this.$message.error(res.msg)
              }
            }).catch((error) => {
            })
          }
        }
      })
    },

  }
}
</script>
<style scoped>
  :deep(.el-form-item__content) {
    display: inline-block;
    text-align: left;
    padding-right: 10%;
  }
  :deep(.el-drawer__title) {
    text-align: left;
  }
  :deep(.el-input),
  :deep(.el-input-number--small),
  :deep(.el-select) {
    width: 100%;
  }
  :deep(#mode .el-form-item__content) {
    line-height: 1;
  }
  :deep(#mode .el-form-item__content div) {
    width: 100%;
  }
  :deep(#mode .el-form-item__content div label) {
    width: 50%;
  }
  :deep(#mode .el-form-item__content div label span) {
    width: 100%;
  }
</style>
